package com.yq.core.facade.impl;

import com.yq.api.comm.ResultHandle;
import com.yq.api.dto.UserTO;
import com.yq.api.service.LoginServiceFacade;
import com.yq.core.dto.UserDO;
import com.yq.core.service.UserService;
import com.yq.core.util.GsonUtil;
import com.yq.core.util.UserDOUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import javax.ejb.EJB;
import javax.ejb.Stateless;

/**
 * Created by yq on 16-7-30.
 */
@Stateless(name = "loginServiceFacade")
public class LoginServiceFacadeImpl implements LoginServiceFacade {
    private static final Log log = LogFactory.getLog(LoginServiceFacadeImpl.class);
    @EJB(beanName = "userService")
    private UserService userService;
    public ResultHandle authenticateUser(UserTO userTO) {
        ResultHandle resultHandle = new ResultHandle();
        if(userTO == null || StringUtils.isBlank(userTO.getUsername()) || StringUtils.isBlank(userTO.getPassword())){
            resultHandle.setMessage("用户名或者密码为空");
            return resultHandle;
        }
        try {
            UserDO userDO= UserDOUtil.toUserDO(userTO);
            UserDO user = userService.getUser(userDO);
            if(user == null || user.getUserId() == null || user.getUserId() < 0){
                resultHandle.setMessage("用户[" + userTO.getUsername() + "]不存在，请注册");
                return resultHandle;
            }
            if(!StringUtils.equals(userTO.getPassword(), user.getPassword())){
                resultHandle.setMessage("用户[" + userTO.getUsername() +"]密码错误，请重新输入");
                return resultHandle;
            }
            //认证成功，回写信息
            UserDOUtil.writeBack(user, userTO);
        } catch (Exception e) {
            log.error("Error while trying to authenticate user " + GsonUtil.toGsonString(userTO), e);
            resultHandle.setMessage(e.getMessage());
        }

        return resultHandle;
    }
}
